package com.wkh.datastructure.stack;

import java.util.Iterator;

public class ArrayStack<E> implements Stack<E>,Iterable<E>{
    private int top = 0;//栈顶指针
    private E[] array;

    public ArrayStack(int capacity) {
        this.array = (E[]) new Object[capacity];
    }

    /**
     * 像栈顶压入元素
     *
     * @param value :待压入值
     * @return true表示压入成功，false表示压入失败
     */
    @Override
    public boolean push(E value) {
        if (isFull()){
            return false;
        }
        array[top] = value;
        top++;
        return true;
    }

    /**
     * 从栈顶弹出元素
     *
     * @return 栈非空返回栈顶元素，栈为空返回null
     */
    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }
        E value = array[top - 1];
        top--;
        return value;
    }

    /**
     * 返回栈顶元素，不弹出
     *
     * @return
     */
    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        E value = array[top - 1];
        return value;
    }

    /**
     * 判断栈是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return top == 0;
    }

    /**
     * 判断栈是否是满的
     *
     * @return
     */
    @Override
    public boolean isFull() {
        return top == array.length;
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = top;
            @Override
            public boolean hasNext() {
                return p > 0;
            }

            @Override
            public E next() {
                E value = array[p-1];
                p--;
                return value;
            }
        };
    }
}
